package com.platform.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.platform.dao.*;
import com.platform.entity.*;
import com.platform.service.CouponService;
import com.platform.utils.CharUtil;
import com.platform.utils.R;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Service实现类
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-19 12:53:26
 */
@Service("couponService")
public class CouponServiceImpl implements CouponService {
    private static final Logger logger = LoggerFactory.getLogger(CouponServiceImpl.class);
    @Autowired
    private CouponDao couponDao;
    @Autowired
    private UserCouponDao userCouponDao;
    @Autowired
    private CouponGoodsDao couponGoodsDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CouponTypeDao couponTypeDao;

    @Override
    public R queryObject(Integer id) {
        //查询优惠券表
        Map couponGoodsMap = new HashMap();
        couponGoodsMap.put("couponId",id);
        CouponEntity couponEntity = couponDao.queryObject(id);
        //查询优惠券商品表
        List<CouponGoodsEntity> couponGoodsList= couponGoodsDao.queryCouponGoodsByCouponId(couponGoodsMap);
        List<Integer> couponGoodsId = couponGoodsList.stream().map(CouponGoodsEntity::getGoodsId).collect(Collectors.toList());
        Map map = new HashMap();
        map.put("couponEntity",couponEntity);
        map.put("couponGoodsId",couponGoodsId);
        return R.ok(map);
    }

    @Override
    public List<CouponEntity> queryList(Map<String, Object> map) {
        return couponDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return couponDao.queryTotal(map);
    }

    @Override
    public int save(CouponEntity couponEntity){
        return couponDao.save(couponEntity);
    }

    @Override
    public void save(Map<String,Object> map) {
        CouponEntity couponEntity = JSON.parseObject(JSON.toJSONString(map.get("couponEntity")), CouponEntity.class);
        couponDao.save(couponEntity);

        //保存在优惠券表
        if (null!=map.get("goodsId")){
            List<Integer> goodsList = (List) map.get("goodsId");
            //保存在优惠券商品表
            for(int i = 0;i<goodsList.size();i++) {
                CouponGoodsEntity couponGoodsEntity = new CouponGoodsEntity();
                int couponId = couponEntity.getId();
                couponGoodsEntity.setCouponId(couponId);
                couponGoodsEntity.setGoodsId(goodsList.get(i));
                couponGoodsDao.save(couponGoodsEntity);
            }
        }

    }

    @Override
    public void update(Map<String, Object> map) {
        //更新优惠券表
        CouponEntity couponEntity = JSON.parseObject(JSON.toJSONString(map.get("couponEntity")), CouponEntity.class);
        couponDao.update(couponEntity);

        //更新优惠券商品表
        if (null!=map.get("goodsId")){
            List<Integer> goodsList = (List) map.get("goodsId");

            //保存在优惠券商品表
            for(int i = 0;i<goodsList.size();i++){
                CouponGoodsEntity couponGoodsEntity = new CouponGoodsEntity();
                int couponId=couponEntity.getId();
                couponGoodsEntity.setCouponId(couponId);
                couponGoodsEntity.setGoodsId(goodsList.get(i));
                couponGoodsDao.save(couponGoodsEntity);
            }

        }
    }

    @Override
    public int update(CouponEntity coupon) {
        return couponDao.update(coupon);
    }

    @Override
    public R delete(Integer id) {
        Map<String,Object> map = new HashMap<>();
        map.put("couponId",id);
        List<UserCouponEntity> couponEntities = userCouponDao.queryList(map);
        //优惠券还没被领
        if (couponEntities==null || couponEntities.size()==0){
            couponDao.delete(id);
            return R.ok();
        }
        return R.error("该优惠券已被用户领取,不能删除!");
    }

    @Override
    public R deleteBatch(Integer[] ids) {
        for (int i =0;i<ids.length;i++){
            Map<String,Object> map = new HashMap<>();
            map.put("couponId",ids[i]);
            List<UserCouponEntity> couponEntities = userCouponDao.queryList(map);
            //优惠券被领 不能删
            if (couponEntities.size()!=0){
                CouponEntity couponEntity = couponDao.queryObject(ids[i]);
                return R.error(couponEntity.getName()+"优惠券已被用户领取,不能删除!");
            }
            couponDao.delete(ids[i]);
        }
        return R.ok();
    }

    @Override
    public R publish(Map<String, Object> params) {
        // 发放方式 0：按订单发放 1：按用户发放 2:商品转发送券 3：按商品发放 4:新用户注册  5：线下发放 6评价好评红包（固定或随机红包）
        Integer sendType = MapUtils.getInteger(params, "sendType");
        Integer couponId = MapUtils.getInteger(params, "couponId");
        CouponEntity couponEntity = couponDao.queryObject(couponId);
        if (null == sendType) {
            return R.error("发放方式不能为空");
        }
        if (null == couponId) {
            return R.error("优惠券不能为空");
        }
        if (1 == sendType) {
            String userIds = MapUtils.getString(params, "userIds"); // 下发用户逗号分割
            if (StringUtils.isEmpty(userIds)) {
                return R.error("用户不能为空");
            }
            //是否发送短信通知
            boolean sendSms = "true".equals(MapUtils.getString(params, "sendSms"));
            for (String strUserId : userIds.split(",")) {
                if (StringUtils.isEmpty(strUserId)) {
                    continue;
                }
                Integer userId = Integer.valueOf(strUserId);
                UserCouponEntity userCouponVo = new UserCouponEntity();
                userCouponVo.setUserId(userId);
                userCouponVo.setCouponId(couponId);
                userCouponVo.setCouponNumber(CharUtil.getRandomString(12));
                userCouponVo.setAddTime(new Date());
                //指定天数
                if (couponEntity.getValidityType()==1){
                    userCouponVo.setUseEndDate(plusDay(couponEntity.getValidityDays()));
                }else{//指定日期
                    userCouponVo.setUseEndDate(couponEntity.getUseEndDate());
                }
                userCouponDao.save(userCouponVo);
                if (sendSms) {
                    UserEntity userEntity = userDao.queryObject(userId);
                    // todo 发送短信

                }
            }
        } else if (3 == sendType) {
            String goodsIds = MapUtils.getString(params, "goodsIds"); // 下发商品逗号分割
            if (StringUtils.isEmpty(goodsIds)) {
                return R.error("商品Id不能为空");
            }
            for (String goodsId : goodsIds.split(",")) {
                if (StringUtils.isEmpty(goodsId)) {
                    continue;
                }
                CouponGoodsEntity couponGoodsVo = new CouponGoodsEntity();
                couponGoodsVo.setCouponId(couponId);
                couponGoodsVo.setGoodsId(Integer.valueOf(goodsId));
                couponGoodsDao.save(couponGoodsVo);
            }
        } else {
            return R.error("此类优惠券不支持手动发放");
        }
        return R.ok("发放成功");
    }

    private  String plusDay(int num) {
        Date oldDate = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            String currdate = format.format(oldDate);
            System.out.println("现在的日期是：" + currdate);
            Calendar ca = Calendar.getInstance();
            ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
            oldDate = ca.getTime();
            String a = format.format(oldDate);
            System.out.println("a"+a);
            System.out.println("增加天数以后的日期：" + a);
            return a;
        }catch (Exception e){
            e.printStackTrace();
        }
        return format.format(oldDate);
    }
}
